import axios from 'axios'
import { message } from 'ant-design-vue'
import router from '@/router'

// 添加错误消息控制变量
let isShowingLoginMessage = false
let isShowingNetworkError = false
let loginMessageTimer = null
let networkErrorTimer = null

// 创建axios实例
const service = axios.create({
  baseURL: 'http://localhost:4000',
  timeout: 150000
})

// 请求拦截器
service.interceptors.request.use(
  config => {
    const token = localStorage.getItem('token')
    if (token) {
      config.headers['sa-token'] = token
    }
    return config
  },
  error => {
    console.error('请求错误:', error)
    return Promise.reject(error)
  }
)

// 显示登录消息的函数
const showLoginMessage = () => {
  if (!isShowingLoginMessage) {
    isShowingLoginMessage = true
    message.error('登录已过期，请重新登录')
    
    if (loginMessageTimer) {
      clearTimeout(loginMessageTimer)
    }
    
    loginMessageTimer = setTimeout(() => {
      isShowingLoginMessage = false
    }, 3000)
    
    localStorage.removeItem('token')
    localStorage.removeItem('loginId')
  }
}

// 显示网络错误消息的函数
const showNetworkError = () => {
  if (!isShowingNetworkError) {
    isShowingNetworkError = true
    message.error('网络连接失败，请检查网络设置')
    
    if (networkErrorTimer) {
      clearTimeout(networkErrorTimer)
    }
    
    networkErrorTimer = setTimeout(() => {
      isShowingNetworkError = false
    }, 3000)
  }
}

// 响应拦截器
service.interceptors.response.use(
  response => {
    const res = response.data
    
    if (res.code === 200) {
      return res
    } else {
      // 401 表示未登录
      if (res.code === 401) {
        showLoginMessage()
      } else {
        // 其他错误码统一使用后端返回的message
        message.error(res.message || '操作失败')
      }
      return Promise.reject(new Error(res.message || '操作失败'))
    }
  },
  error => {
    // 网络错误或请求被取消
    if (!error.response) {
      showNetworkError()
      return Promise.reject(error)
    }
    
    // 服务器返回错误
    const res = error.response.data
    if (res.code === 401) {
      showLoginMessage()
    } else {
      message.error(res.message || '操作失败')
    }
    return Promise.reject(error)
  }
)

// 封装请求方法
export const request = {
  get(url, params) {
    return service.get(url, { params })
  },
  
  post(url, data, config = {}) {
    return service.post(url, data, config)
  },
  
  put(url, data) {
    return service.put(url, data)
  },
  
  delete(url, params) {
    return service.delete(url, { params })
  }
}

export default service 